<?php
namespace app\admin666\controller;

use think\View;
class Make{
    
    /**
     * @var \think\View 视图类实例
     */
    protected $view;
    
    protected $temp_path = '/';
    
    
    /* 空操作，用于输出404页面 */
    public function _empty() {
        return 404;
    }
    
    public function __construct(){
        $cfg = [
            'view_path' => './template/',
            'taglib_pre_load' => 'app\common\taglib\Xc',
        ];
        $this->view = View::instance($cfg, config('view_replace_str'));
        
        $base    = request()->root();
        $root    = strpos($base, '.') ? ltrim(dirname($base), DS) : $base;
        if ('' != $root) {
            $root = '/' . ltrim($root, '/');
        }
        
        config('web_path',$root.'/');
        
        /* 读取数据库中的配置 */
        $config =   cache('DB_CONFIG_DATA');
        if(!$config){
            $config =  config_lists();
            cache('DB_CONFIG_DATA',$config);
        }
        config($config); //添加配置
        
        $this->assign('vars',$config);
    }
    
    
    /**
    * 首页
    * @date: 2018年8月20日 下午1:40:41
    * @author: xiaocui
    * @param: variable
    * @return:
    */
    public function index(){
        
        $this->assign('title',config('seo_title'));
        $this->assign('keywords',config('seo_keywords'));
        $this->assign('description',config('seo_description'));
        
        $html = $this->fetch($this->temp_path.'index');
        
        file_put_contents('index.html', $html);
        exit('已完成：<a href="'.config('web_path').'index.html" target="_blank">'.config('web_path').'index.html 浏览</a>');
    }
    
    /**
    * 列表页
    * @date: 2018年8月20日 下午1:40:59
    * @author: xiaocui
    * @param: variable
    * @return:
    */
    private function lists($tid){
        //$tid = intval(input('id',0));
        $tinfo = db('column')->find($tid);
        
        if($tid <= 0 || empty($tinfo)){
            return 2;
        }
        if($tinfo['type'] == 3){
            return 2;
        }
        $tmep_file = $tinfo['type'] == 1?$tinfo['temp_index']:$tinfo['temp_list'];
        $minfo = db('models')->find($tinfo['mid']);
        
        $col = db('column')->field('id,pid,type,title,dir')->where(['mid'=>$tinfo['mid']])->order('id asc')->select();
        import('util.Tree');
        $cids = \Tree::getChildsIds($col,$tid,true);
        $parents = \Tree::getParents($col,$tid,true);
        $this->assign('parents',get_pos($tid,$parents));
        
        $topid = 0;
        foreach ($parents as $val){
            if($val['pid']==0){
                $topid = $val['id'];
            }
        }
        $tinfo['topid'] = $topid;
        
        $dir = !empty($tinfo['dir'])?$tinfo['dir']:'html';
        $path = config('web_path').''.$dir.'/list';
        
        if($tinfo['type'] == 2){
            $page_size = $tinfo['page_size']>0?$tinfo['page_size']:10;
            $map['tid'] = ['in',$cids];
            $list = db($minfo['name'])->where($map)
            ->paginate($page_size,false,[
                'type'=>'\app\common\exception\StaticPage',
                'path'=>$path,
                'tid'=>$tid,
                'query'=>[]]
            );
            $page = $list->render();
            $data = $list->toArray();
            $list = $data['data'];
            foreach ($list as $key=>$val){
                $list[$key]['url'] = rurl(['type'=>10,'dir'=>$tinfo['dir']],'view',['id'=>$val['id']]);
            }
            
            $this->assign('list', $list);
            $this->assign('page', $page);
        }
        
        $this->assign('title',$tinfo['title'].' - '.config('seo_title'));
        $this->assign('keywords',!empty($tinfo['keywords'])?$tinfo['keywords']:config('seo_keywords'));
        $this->assign('description',!empty($tinfo['description'])?$tinfo['description']:config('seo_description'));
        $this->assign('tinfo',$tinfo);
        $tmep_file = substr($tmep_file,0,-5);
        $html = $this->fetch($this->temp_path.$tmep_file);
        
        if(!is_dir($dir)){
            @mkdir($dir);
        }
        
        if($tinfo['type'] == 1){
            $fname = $dir.'/index.html';
        }else{
            $page = intval(input('page',1));
            $fname = $dir.'/list-'.$tid.'-'.$page.'.html';
        }
        
        file_put_contents($fname, $html);
        if(isset($list) && empty($list)){
            return 2;
        }elseif($tinfo['type'] == 1){
            return 2;
        }else{
            return 1;
        }
    }
    
    /**
    * 内容页
    * @date: 2018年8月20日 下午1:41:39
    * @author: xiaocui
    * @param: variable
    * @return:
    */
    private function view($id){
        //$id = intval(input('id',0));
        $ainfo = db('arctiny')->where(['aid'=>$id])->find();
        if(empty($ainfo)){
            return 1;
        }
        
        $tinfo = db('column')->find($ainfo['tid']);
        if(empty($tinfo)){
            return 1;
        }
        
        $minfo = db('models')->find($tinfo['mid']);
        
        $info = db($minfo['name'])->where(['display'=>1,'id'=>$id])->find();
        if(empty($info)){
            return 1;
        }
        
        $this->assign('title',$info['title'].' - '.$tinfo['title'].' - '.config('seo_title'));
        $this->assign('keywords',!empty($info['keywords'])?$info['keywords']:config('seo_keywords'));
        $this->assign('description',!empty($info['description'])?$info['description']:config('seo_description'));
        $this->assign('parents',get_pos($tinfo['id']));
        $this->assign('tinfo',$tinfo);
        $this->assign('info',$info);
        
        $tmep_file = trim($tinfo['temp_view']) != ''?$tinfo['temp_view']:'default_view.html';
        $tmep_file = substr($tmep_file,0,-5);
        $html = $this->fetch($this->temp_path.$tmep_file);
        
        $dir = !empty($tinfo['dir'])?$tinfo['dir']:'html';
        if(!is_dir($dir)){
            @mkdir($dir);
        }
        $fname = $dir.'/view-'.$id.'.html';
        file_put_contents($fname, $html);
        return 1;
    }
    
    /**
    * 批量生成栏目
    * @date: 2018年8月21日 下午5:34:22
    * @author: xiaocui
    * @param: variable
    * @return:
    */
    public function batch_list(){
        $tid = intval(input('tid',0));
        $make = intval(input('make',0));
        $code = intval(input('code',0));
        $page = intval(input('page',0));
        
        if($make == 1){
            if($tid == 0){
                $tinfo = db('column')->field('id,type,title')->where(['id'=>['gt',$tid]])->order('id asc')->find();
                $nid = intval($tinfo['id']);
                $page = 0;
            }else{
                $nid = $tid;
                $tinfo = db('column')->field('id,type,title')->find($nid);
            }
        
            if($nid > 0){
                $code = $this->lists($nid);
                if($code == 2){
                    $page = 0;
                    $tinfo = db('column')->field('id,type,title')->where(['id'=>['gt',$tid]])->order('id asc')->find();
                    $nid = intval($tinfo['id']);
                    if(empty($tinfo) && $nid == 0){
                        $data['code'] = 0;
                        $data['msg'] = "已完成";
                        return json($data);
                    }
                }
                $page = $page + 1;
                $data['code'] = 1;
                $data['nid'] = $nid;
                $data['url'] = url('batch_list',['make'=>1,'code'=>$code,'tid'=>$nid,'page'=>$page]);
                $data['page'] = $page;
        
                if($tinfo['type']==2){
                    $data['msg'] = "栏目：{$tinfo['title']}，第{$page}页";
                }else{
                    $data['msg'] = "栏目：{$tinfo['title']}";
                }
            }else{
                $data['code'] = 0;
                $data['msg'] = "已完成";
            }
            return json($data);
        }
    }
    
    /**
    * 批量生成内容页
    * @date: 2018年8月21日 下午5:06:23
    * @author: xiaocui
    * @param: variable
    * @return:
    */
    public function batch_view(){
        $make = intval(input('make',0));
        $page = intval(input('page',1));
        
        if($make == 1){
            $page_size = 100;
            $list_row = ($page-1)*$page_size;
            $list = db('arctiny')->field('id,aid')->order('id asc')->limit("{$list_row},{$page_size}")->select();
            $count = db('arctiny')->count('id');
            $page_count = ceil($count/$page_size);
            if(!empty($list)){
                foreach ($list as $val){
                    $this->view($val['aid']);
                }
                
                $prop = round($page/$page_count,2) * 100;
                $page = $page+1;
                
                $data['code'] = 1;
                $data['msg'] = "已完成{$prop}%";
                $data['url'] = url('batch_view',['make'=>1,'page'=>$page]);
            }else{
                $data['code'] = 0;
                $data['msg'] = '已完成';
            }
            return json($data);
        }
    }
    
    
    /**
     * 加载模板输出
     * @access protected
     * @param  string $template 模板文件名
     * @param  array  $vars     模板输出变量
     * @param  array  $replace  模板替换
     * @param  array  $config   模板参数
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        return $this->view->fetch($template, $vars, $replace, $config);
    }
    
    /**
     * 模板变量赋值
     * @access protected
     * @param  mixed $name  要显示的模板变量
     * @param  mixed $value 变量的值
     * @return $this
     */
    protected function assign($name, $value = '')
    {
        $this->view->assign($name, $value);
    
        return $this;
    }
}